<template>
  <div>
    <div v-show="domainList.length" class="config-table">
      <el-table :data="domainList" stripe style="width: 100%">
        <el-table-column prop="from" label="from" width="180" />
        <el-table-column prop="name" label="name" width="180" />
        <el-table-column prop="to" label="to" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-icon color="#409EFC" class="no-inherit" size="large" @click="deleteList(row)">
              <delete />
            </el-icon>
          </template>
        </el-table-column>
      </el-table>
      <el-divider></el-divider>
    </div>
    <el-form
      ref="formRef"
      :inline="true"
      label-suffix=":"
      :model="nextConfigItem"
      :rules="formRules"
    >
      <el-form-item label="把" prop="from">
        <el-autocomplete
          v-model="nextConfigItem.from"
          :fetch-suggestions="querySearch"
          placeholder="输入目标站点"
          @select="handleSelect(formRef)"
        />
      </el-form-item>
      <el-form-item label="的cookie" prop="name">
        <el-input v-model="nextConfigItem.name"></el-input>
      </el-form-item>
      <el-form-item label="同步到" prop="to">
        <el-input v-model="nextConfigItem.to"></el-input>
      </el-form-item>
    </el-form>
    <div class="submit-content">
      <el-button @click="onSubmit(formRef)">添加监控</el-button>
    </div>
    <el-alert
      v-if="alertText"
      :title="alertText"
      type="warning"
      show-icon
      :closable="false"
    ></el-alert>
  </div>
</template>

<script setup>
import { Delete } from "@element-plus/icons-vue";
import { ref, reactive, onMounted } from "vue";

const initItem = {
  from: "",
  name: "WEBID",
  to: "http://localhost",
};
// 添加domain的form数据
const nextConfigItem = reactive(initItem);

const formRef = ref();

const formRules = reactive({
  from: [{ required: true, message: "请输入源站点", trigger: "blur" }],
  to: [{ required: true, message: "请输入目标站点", trigger: "blur" }],
  name: [{ required: true, message: "请输入cookie名称", trigger: "blur" }],
});
let domainList = reactive([]);
let alertText = ref(null);

onMounted(async () => {
  // 获取存储的domainList
  const { domainList: domainObj } = await chrome.storage.local.get(["domainList"]);
  const storArr = Object.keys(domainObj).map(key => domainObj[key]);
  domainList.push(...storArr);

  // 监听cookie变化
  // chrome.runtime.sendMessage("addCookiesChangeEvent");
});

function onSubmit(formEl) {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      const str = JSON.stringify(nextConfigItem);
      alertText.value = null;
      if (domainList.some(e => e.id === str)) {
        alertText.value = "此配置项已存在于监控列表中，无需重复添加哦";
        return;
      }
      const config = {
        ...nextConfigItem,
        id: str,
      };
      const result = await updateCookie(config);
      // 如果不存在该cookie显示提示信息；存在再执行后续逻辑
      if (!result) {
        alertText.value = `源站点不存在cookie(${config.name}),但仍为你加入到了监控列表`;
      }
      domainList.push(config);
      await updateStorage(domainList);
      // form表单恢复默认
      // formRef.resetFields();
      // } else {
      // }

      const list = await chrome.storage.local.get(["domainList"]);
      console.log("list", list);
    }
  });
}
async function deleteList(row) {
  alertText.value = null;
  const index = domainList.findIndex(e => e.id === row.id);
  domainList.splice(index, 1);
  await updateStorage(domainList);
}

async function updateStorage(list) {
  await chrome.storage.local.set({ domainList: list });
}

async function updateCookie(config) {
  const cookie = await chrome.cookies.get({
    url: addProtocol(config.from),
    name: config.name,
  });
  return cookie ? await setCookie(cookie, config) : null;
}

const restaurants = reactive([
  {
    value: "http://gdios.dev.ge.cn",
  },
  {
    value: "http://192.168.10.24",
  },
]);
const querySearch = (queryString, cb) => {
  const results = queryString ? restaurants.filter(e => e.value === queryString) : restaurants;
  cb(results);
};

function handleSelect(formEl) {
  formEl.clearValidate("from");
}

// 增加协议头
function addProtocol(uri) {
  return uri.startsWith("http") ? uri : "http://" + uri;
}
// 去除协议头
function removeProtocol(uri) {
  return uri.startsWith("http") ? uri.replace("https://", "").replace("http://", "") : uri;
}

function setCookie(cookie, config) {
  return chrome.cookies.set({
    url: addProtocol(config.to),
    domain: removeProtocol(config.to),
    name: cookie["name"],
    path: cookie["path"],
    value: cookie["value"],
    // expirationDate: cookie["expirationDate"],
    // secure: true,
    // sameSite: "no_restriction", // 不阻止跨域cookie
  });
}
</script>

<style lang="less" scoped>
.submit-content {
  text-align: center;
  padding-bottom: 12px;
}
</style>
